/*
 * @Description:用户信息处理模块
 * @Author: 小雨
 * @Date: 2024-07-04 17:44:25
 * @LastEditTime: 2024-07-05 15:43:49
 * @LastEditors: 小雨
 */
const db = require('../db/index');
const bcryptjs = require('bcryptjs');

exports.getUserInfo = (req, res) => {
    const sql = 'select id, username  , email , user_pic from ev_users where id=?';
    //只要token express-jwt身份认证成功req.auth就会挂载一个id
    db.query(sql, req.auth.id, (err, result) => {
        //执行失败
        if (err) return res.cc(err);
        //执行成功但是结果为空
        if (result.length !== 1) return res.cc('获取用户失败');
        res.send({
            status: 0,
            message: '获取用户信息成功',
            data: result[0],
        });
    });
};

exports.updateUserInfo = (req, res) => {
    const sql = 'update ev_users set ? where id = ?';
    db.query(sql, [req.body, req.body.id], (err, result) => {
        if (err) return res.cc(err);
        if (result.affectedRows !== 1) return res.cc('用户更新失败');
        res.cc('用户更新信息成功', 0);
    });
};

exports.updatepwd = (req, res) => {
    const sql = 'select * from ev_users where id =?';
    //通过token解析出来的id去查询该用户是否存在
    db.query(sql, req.auth.id, (err, result) => {
        if (err) return res.cc(err);
        if (result.length !== 1) return res.cc('用户不存在');

        //判断旧密码是否正确
        const isSame = bcryptjs.compareSync(req.body.oldPwd, result[0].password);
        if (!isSame) return res.cc('旧密码不正确');
        //更新密码
        const sql = 'update ev_users set password = ? where id=?';
        //加密新密码
        const newPwd = bcryptjs.hashSync(req.body.newPwd, 10);
        db.query(sql, [newPwd, req.auth.id], (err, result) => {
            if (err) return res.cc(err);
            if (result.affectedRows !== 1) return res.cc('密码更新失败');
            res.cc('密码更新信息成功', 0);
        });
    });
};

exports.deletecate = (req, res) => {
    //进行标记删除
    const sql = 'update ev_users set user_pic=1 where id =?';
    db.query(sql, req.params.id, (err, result) => {
        if (err) return res.cc(err);
        if (result.affectedRows !== 1) return res.cc('删除失败');
        res.cc('删除成功成功', 0);
    });
};
